package com.xe.gae;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import groovy.servlet.TemplateServlet;
import groovy.text.SimpleTemplateEngine;
import groovy.text.Template;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.groovy.control.CompilationFailedException;


import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Text;
import com.xe.gae.control.XEBlobstoreService;
import com.xe.gae.control.XEDataStorageService;
import com.xe.gae.control.XEResourcesManager;
import com.xe.gae.model.XEResource;
import com.xe.util.XConstants;



public class XEngine {
	
	
  
	XEResourcesManager rm= new XEResourcesManager();
	XEDataStorageService dss = new XEDataStorageService();
	 
	

	public void run (HttpServletRequest req, HttpServletResponse res){
		String path =  req.getServletPath();
		
		run(path,req,res);
	}

	
		public void run (String path,HttpServletRequest req, HttpServletResponse res){
			XEResourcesManager rm= new XEResourcesManager();
			XEResource root = rm.getRoot();
			Key parent = root.getTree().getKey();
			XEResource x = (XEResource) dss.findByKey(parent,XEResource.class, path);
			
			if (x!=null){
				if(x.getPath().equalsIgnoreCase(root.getPath()))
				{
					//todo:buscar el que esta seleccionado como default, o algo del disco
					try {
						res.getWriter().write("XTREME ENGINE IS RUNNING.");
						res.getWriter().write("<a href='_xe/admin'>Go to admin Console</a>");
						res.setContentType("text/html");
						return;
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				else {
					run (x,req,res);
				}
			}
			else{
				System.out.println("Resource No found :" + path);
			}
	}
	
		public void run (XEResource resource,HttpServletRequest req, HttpServletResponse res){
	
		String path=	resource.getPath();
		String extension = rm.getFileExtension(path);
		
		String stmime = resource.getMimeType();
		
		if(XConstants.MIMETYPE_4_GROOVY.equals(stmime)){ 
			runGroovy(resource,req,res);
		}
		else if(XConstants.MIMETYPE_4_GROOVY_TEMPLATE.equals(stmime)){ 
			runGroovyTemplate(resource,req,res);
		} 
		else if(resource.getSource()!=null){ 
			serveAsText(resource, req, res);
		} 
		else {
			serveAsBlob(resource, req, res);
		}
	}
	
	public void runGroovy (XEResource resource,HttpServletRequest req, HttpServletResponse res){
		
		Binding binding = new Binding();
		binding.setVariable("request", req);
		binding.setVariable("response", res);
		GroovyShell shell = new GroovyShell(binding);

		Object value = shell.evaluate(resource.getSource().getValue());
			
		//serveAsText(resource, req, res);
	}

	public void runGroovyTemplate (XEResource resource,HttpServletRequest req, HttpServletResponse res){
		SimpleTemplateEngine ste = new SimpleTemplateEngine();
		Map<String,Object> binding = new HashMap<String,Object>();
		binding.put("request", req);
		binding.put("response", req);
		binding.put("session", req.getSession());

		Template t;
		try {
			t = ste.createTemplate(resource.getSource().getValue());
			t.make(binding).writeTo(res.getWriter());
		} catch (Exception e){
			e.printStackTrace();
			try {
				e.printStackTrace(res.getWriter());
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
		}
		
		

		
		
	}
	
	public void serveAsText (XEResource resource,HttpServletRequest req, HttpServletResponse res){
		
		try {
			Text source = resource.getSource();
			if(source!=null)
			res.getWriter().write(source.getValue());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	public void serveAsBlob (XEResource resource,HttpServletRequest req, HttpServletResponse res){
			
		BlobKey blobKey = resource.getBlobKey();
		XEBlobstoreService bs = new XEBlobstoreService();
        //BlobInfoFactory bi = new BlobInfoFactory();
        //String fname = bi.loadBlobInfo(blobKey).getFilename();
        //res.setContentType("application/x-download");
        //res.setHeader("Content-Disposition", "attachment; filename=" + fname);
        
        bs.serve(blobKey, res);
		
	}
	
	
	
}
